package me.zhengjie.modules.website.controller;

import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.website.domain.UserColumn;
import me.zhengjie.modules.website.service.UserColumnService;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import me.zhengjie.modules.website.domain.ColumnTable;
import me.zhengjie.modules.website.service.ColumnTableService;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.GetMapping;
import me.zhengjie.modules.website.domain.PageResult;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author system
 * @since 2024-09-26 16:06:29
 */
@RestController
@RequestMapping("/api/columnTable")
@Api(tags = " 网页-栏目管理")
public class ColumnTableController {

    @Autowired
    private ColumnTableService columnTableService;

    @Autowired
    private UserColumnService userColumnService;

    @Autowired
    private RoleService roleService;

    /**
     * 分页查询
     *
     * @param params
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询", produces = "application/json")
    @PostMapping("/findPage")
    public ResponseEntity<PageResult<ColumnTable>> findPage(
            @RequestBody ColumnTable params,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate,
            Pageable pageable) {

        Sort sort = Sort.by(Sort.Direction.ASC, "sortOrder"); // 按照 sortOrder 字段升序排序
        Pageable selPage = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sort);

        // 调用服务层方法，传递可选的时间条件
        PageResult<ColumnTable> result = columnTableService.findPage(params, startDate, endDate, selPage);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 分页查询
     *
     * @param params
     * @return
     */
    @ApiOperation(value = "展示端-分页查询", notes = "展示端-分页查询", produces = "application/json")
    @PostMapping("/website/findPage")
    public ResponseEntity<PageResult<ColumnTable>> websiteByFindPage(@RequestBody ColumnTable params,
                                                                     @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")LocalDateTime startDate,
                                                                     @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")LocalDateTime endDate,
                                                                     Pageable pageable) {
        Sort sort = Sort.by(Sort.Direction.ASC, "sortOrder"); // 按照name字段升序排序
        Pageable selPage = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sort);
        PageResult<ColumnTable> result = columnTableService.findPage(params, startDate, endDate, selPage);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 列表查询
     *
     * @param params
     * @return
     */
    @ApiOperation(value = "列表查询", notes = "列表查询", produces = "application/json")
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功")})
    @PostMapping("/website/findList")
    public ResponseEntity<List<ColumnTable>> findList(@RequestBody ColumnTable params) {
        List<ColumnTable> result = columnTableService.findList(params);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "查询", notes = "查询详情")
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功")})
    @GetMapping("/website/findById/{id}")
    public ResponseEntity<ColumnTable> findById(@PathVariable("id") Long id) {
        ColumnTable columnTable = columnTableService.findById(id);
        return ResponseEntity.ok(columnTable);
    }

    /**
     * 新增
     *
     * @param columnTable
     * @return
     */
    @ApiOperation(value = "新增", notes = "新增数据")
    @PostMapping("/insert")
    public ResponseEntity<ColumnTable> insert(@Validated @RequestBody ColumnTable columnTable) {
        columnTable.setImgPath(columnTable.getImgPathList().stream().collect(Collectors.joining(",")));
        ColumnTable result = columnTableService.insert(columnTable);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 修改
     *
     * @param columnTable
     * @return
     */
    @ApiOperation(value = "修改", notes = "修改数据")
    @PutMapping("/update")
    public ResponseEntity<ColumnTable> update(@Validated @RequestBody ColumnTable columnTable) {
        columnTable.setImgPath(columnTable.getImgPathList().stream().collect(Collectors.joining(",")));

        System.out.println(columnTable);
        ColumnTable result = columnTableService.update(columnTable);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除", notes = "删除数据")
    @DeleteMapping("/del/{id}")
    public ResponseEntity<Object> delete(@PathVariable("id") Long id) {
        columnTableService.delete(id);
        return new ResponseEntity<>("Successful", HttpStatus.OK);
    }

    /**
     * 树结构获取所有栏目
     *
     * @return
     */
    @GetMapping("/website/columns")
    @ApiOperation(value = "网页-树结构获取所有栏目", notes = "网页-树结构获取所有栏目")
    public ResponseEntity<List<ColumnTable>> getAllColumns() {

        return new ResponseEntity<>(columnTableService.getAllColumnsWithChildren(), HttpStatus.OK);

    }

    /**
     * 根据权限树结构获取所有栏目
     * @return
     *//*
    @GetMapping("/columns")
    @ApiOperation(value = "管理平台-根据权限树结构获取所有栏目", notes = "网页-树结构获取所有栏目")
    public ResponseEntity<List<ColumnTable>> getColumns() {
        // 获取当前用户 ID

        List<RoleSmallDto> byUsersId = roleService.findByUsersId(SecurityUtils.getCurrentUserId());

        List<UserColumn> userColumns = new ArrayList<>();
        for (RoleSmallDto roleSmallDto : byUsersId) {
            // 根据用户 ID 查询 UserColumn 表中的栏目 ID
            UserColumn userColumn = new UserColumn();
            userColumn.setRoleId(roleSmallDto.getId());
            userColumns.addAll(userColumnService.findList(userColumn));
        }

        // 提取所有子级栏目 ID
        List<Long> childColumnIds = userColumns.stream()
                .map(UserColumn::getColumnId)
                .collect(Collectors.toList());

        // 查询所有相关栏目（递归向上直到根节点）
        List<ColumnTable> allColumns = fetchAllColumnsRecursively(childColumnIds);

        // 构建树状结构
        List<ColumnTable> tree = buildTree(allColumns);

        return new ResponseEntity<>(tree, HttpStatus.OK);
    }

    private List<ColumnTable> fetchAllColumnsRecursively(List<Long> columnIds) {
        // 查询当前层级的栏目
        List<ColumnTable> currentColumns = columnTableService.findByIds(columnIds);

        // 提取父级栏目 ID
        List<Long> parentIds = currentColumns.stream()
                .map(ColumnTable::getParentColumnId)
                .filter(Objects::nonNull)
                .filter(parentId -> parentId != 0) // 排除根节点
                .distinct()
                .collect(Collectors.toList());

        if (parentIds.isEmpty()) {
            // 如果没有更多父级栏目，返回当前层级的栏目
            return currentColumns;
        }

        // 递归查询父级栏目
        List<ColumnTable> parentColumns = fetchAllColumnsRecursively(parentIds);

        // 合并当前层级和父级栏目
        currentColumns.addAll(parentColumns);

        return currentColumns;
    }

    private List<ColumnTable> buildTree(List<ColumnTable> columns) {
        // 创建一个 Map，过滤掉重复的 columnId
        Map<Long, ColumnTable> columnMap = columns.stream()
                .collect(Collectors.toMap(
                        ColumnTable::getColumnId,
                        column -> column,
                        (existing, duplicate) -> existing // 如果有重复，保留第一个
                ));

        // 用于存储最终的树结构
        List<ColumnTable> rootColumns = new ArrayList<>();

        // 遍历所有的栏目数据，构建父子关系
        for (ColumnTable column : columnMap.values()) {
            if (column.getParentColumnId() == null || column.getParentColumnId() == 0) {
                // 如果是根节点，加入到 rootColumns 中
                rootColumns.add(column);
            } else {
                // 非根节点，找到父节点并加入其 secondLevelColumns 中
                ColumnTable parent = columnMap.get((long) column.getParentColumnId());
                if (parent != null) {
                    if (parent.getSecondLevelColumns() == null) {
                        parent.setSecondLevelColumns(new ArrayList<>());
                    }
                    parent.getSecondLevelColumns().add(column);
                    // 对子节点排序
                    parent.getSecondLevelColumns().sort(Comparator.comparing(ColumnTable::getSortOrder));
                }
            }
        }

        // 对根节点排序
        rootColumns.sort(Comparator.comparing(ColumnTable::getSortOrder));

        return rootColumns;
    }*/

    @GetMapping("/columns")
    @ApiOperation(value = "管理平台-根据权限树结构获取所有栏目", notes = "网页-树结构获取所有栏目")
    public ResponseEntity<List<ColumnTable>> getColumns() {
        // 获取当前用户 ID
        Long currentUserId = SecurityUtils.getCurrentUserId();
        List<RoleSmallDto> roles = roleService.findByUsersId(currentUserId);

        List<UserColumn> userColumns = new ArrayList<>();
        for (RoleSmallDto role : roles) {
            // 根据用户 ID 查询 UserColumn 表中的栏目 ID
            UserColumn userColumn = new UserColumn();
            userColumn.setRoleId(role.getId());
            userColumns.addAll(userColumnService.findList(userColumn));
        }

        // 提取所有子级栏目 ID
        List<Long> childColumnIds = userColumns.stream()
                .map(UserColumn::getColumnId)
                .collect(Collectors.toList());

        // 查询所有相关栏目（递归向上直到根节点）
        List<ColumnTable> allColumns = fetchAllColumnsRecursively(childColumnIds);

        // 构建树状结构
        List<ColumnTable> tree = buildTree(allColumns);

        return new ResponseEntity<>(tree, HttpStatus.OK);
    }

    private List<ColumnTable> fetchAllColumnsRecursively(List<Long> columnIds) {
        // 查询当前层级的栏目
        List<ColumnTable> currentColumns = columnTableService.findByIds(columnIds);

        // 提取父级栏目 ID
        List<Long> parentIds = currentColumns.stream()
                .map(ColumnTable::getParentColumnId)
                .filter(Objects::nonNull)
                .filter(parentId -> parentId != 0) // 排除根节点
                .distinct()
                .collect(Collectors.toList());

        if (parentIds.isEmpty()) {
            // 如果没有更多父级栏目，返回当前层级的栏目
            return currentColumns;
        }

        // 递归查询父级栏目
        List<ColumnTable> parentColumns = fetchAllColumnsRecursively(parentIds);

        // 合并当前层级和父级栏目
        currentColumns.addAll(parentColumns);

        return currentColumns;
    }

    private List<ColumnTable> buildTree(List<ColumnTable> columns) {
        // 创建一个 Map，过滤掉重复的 columnId
        Map<Long, ColumnTable> columnMap = columns.stream()
                .collect(Collectors.toMap(
                        ColumnTable::getColumnId,
                        column -> column,
                        (existing, duplicate) -> existing // 如果有重复，保留第一个
                ));

        // 用于存储最终的树结构
        List<ColumnTable> rootColumns = new ArrayList<>();

        // 遍历所有的栏目数据，构建父子关系
        for (ColumnTable column : columnMap.values()) {
            if (column.getParentColumnId() == null || column.getParentColumnId() == 0) {
                // 如果是根节点，加入到 rootColumns 中
                rootColumns.add(column);
            } else {
                // 非根节点，找到父节点并加入其 secondLevelColumns 中
                ColumnTable parent = columnMap.get((long) column.getParentColumnId());
                if (parent != null) {
                    if (parent.getSecondLevelColumns() == null) {
                        parent.setSecondLevelColumns(new ArrayList<>());
                    }
                    parent.getSecondLevelColumns().add(column);
                    // 对子节点排序
                    parent.getSecondLevelColumns().sort(Comparator.comparing(ColumnTable::getSortOrder));
                }
            }
        }

        // 对根节点排序
        rootColumns.sort(Comparator.comparing(ColumnTable::getSortOrder));

        return rootColumns;
    }



}
